#include <iostream>
#include <filesystem> // C++17
#include <fstream>
#include <string>
#include <format> // C++20

namespace fs = std::filesystem;

int countLinesInFile(const fs::path &filePath)
{
    std::ifstream file(filePath);
    if (!file.is_open())
    {
        std::cerr << "Error opening file: " << filePath << std::endl;
        return 0;
    }

    int lineCount = 0;
    std::string line;
    while (std::getline(file, line))
    {
        ++lineCount;
    }
    file.close();
    return lineCount;
}

int countLinesInDirectory(const fs::path &directoryPath)
{
    if (!fs::exists(directoryPath))
    {
        std::cerr << "Directory does not exist: " << directoryPath << std::endl;
        return 0;
    }

    if (!fs::is_directory(directoryPath))
    {
        std::cerr << "Provided path is not a directory: " << directoryPath << std::endl;
        return 0;
    }

    int totalLines = 0;
    for (const auto &entry : fs::recursive_directory_iterator(directoryPath))
    {
        if (fs::is_regular_file(entry.path()))
        {
            int fileLines = countLinesInFile(entry.path());
            // std::cout << "File: " << entry.path().filename() << " has " << fileLines << " lines." << std::endl;
            // 使用 std::format 格式化输出
            std::cout << std::format("File: {:<30} has {:>5} lines.\n",
                                     entry.path().filename().string(),
                                     fileLines);
            totalLines += fileLines;
        }
    }
    return totalLines;
}

int main()
{
    std::string directoryPath;
    std::cout << "Enter the directory path: ";
    std::cin >> directoryPath;

    int totalLines = countLinesInDirectory(directoryPath);
    std::cout << "Total lines in directory: " << totalLines << std::endl;

    system("pause");
    return 0;
}
